import VuiElement from '@/components/vui/base/element';
import VuiDropdownItem from '.';

/**
 * 下拉菜单选项-带子菜单
 */
export default class VuiDropdownComboItem extends VuiElement {
  constructor(id, title, icon, dropdown) {
    super();
    const button = VuiDropdownItem.newInstance(id, title, icon, true);
    this._config = { button, dropdown };
    this._className = {
      container: 'vui-dropdown-combo'
    };
  }

  initUI() {
    const config = this._config;
    const { button, dropdown } = config;
    this.initContainer();

    this.append([button, dropdown]);
    // 二级菜单底部对齐
    dropdown.removeProperty('top');
    dropdown.setProperty('bottom', '0px');
    button.setClickListener(evt => {
      dropdown.toggle();
      evt.stopPropagation();
    });
    dropdown.setOnShow(evt => {
      // 二级菜单超出屏幕右侧时 重设显示到一级菜单左侧
      const width = dropdown.getWidth();
      const bounds = button.container.getBoundingClientRect();
      const clientWidth = document.documentElement.clientWidth;
      if (bounds.x + bounds.width + width > clientWidth) {
        dropdown.setTopLeft(null, -(width + 12));
      }
    });
  }
}
